package com.qiuzhiyi.activity;

import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.li.utils.VerifyUtil;
import com.li.widget.TopNavigationBar;
import com.qiuzhiyi.R;
import com.qiuzhiyi.base.QZYBaseActivity;
import com.qiuzhiyi.cache.HumanCache;
import com.qiuzhiyi.item.BaseItem;
import com.qiuzhiyi.item.HumanItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.qiuzhiyi.net.SelectorObserver;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/11/14 0014
 * Description: 重置密码界面
 */

public class ResetPwdActivity extends QZYBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_msg)
    EditText mEtMsg;
    @BindView(R.id.txt_get_msg)
    TextView mTxtGetMsg;
    @BindView(R.id.et_pwd)
    EditText mEtPwd;
    @BindView(R.id.et_pwd_a)
    EditText mEtPwdA;
    @BindView(R.id.txt_reset_pwd)
    TextView mTxtResetPwd;
    private Count mCount;

    private EventHandler mEventHandler;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reset_pwd;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mCount = new Count(60 * 1000 + 16, 1000);
        mEventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                    }
                });
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        //成功后更新用户信息
                        resetPwd(mEtPhone.getText().toString(), mEtPwd.getText().toString());
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        mCount.start();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("获取验证码成功");

                            }
                        });
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("请正确填写手机号和验证码");
                        }
                    });
                }

            }
        };
        SMSSDK.registerEventHandler(mEventHandler);
    }

    @OnClick({R.id.txt_get_msg, R.id.txt_reset_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_get_msg:
                if (VerifyUtil.checkPhone(mEtPhone.getText().toString())) {
                    SMSSDK.getVerificationCode("+86", mEtPhone.getText().toString());
                    showLoadingDialog("正在获取验证码");
                } else {
                    showToast("请填写正确手机号");
                }
                break;
            case R.id.txt_reset_pwd:
                if (isEmpty(mEtPhone) || isEmpty(mEtMsg) || isEmpty(mEtPwd) || isEmpty(mEtPwdA)) {
                    showToast("请将内容填写完整");
                    return;
                }

                if (mEtPwd.getText().toString().length() < 6 || mEtPwdA.getText().toString().length() < 6) {
                    showToast("密码不低于6位");
                    return;
                }
                if (!mEtPwd.getText().toString().equals(mEtPwdA.getText().toString())) {
                    showToast("两次密码输入不一样");
                    return;
                }

                SMSSDK.submitVerificationCode("+86", mEtPhone.getText().toString(), mEtMsg.getText().toString());
                showLoadingDialog("正在登录");
                break;
        }
    }

    private class Count extends CountDownTimer {

        Count(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTxtGetMsg.setEnabled(false);
            String txt = String.valueOf(millisUntilFinished / 1000) + "秒后重新获取";
            mTxtGetMsg.setText(txt);
        }

        @Override
        public void onFinish() {
            mTxtGetMsg.setEnabled(true);
            mTxtGetMsg.setText("重新获取验证码");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCount.cancel();
        SMSSDK.unregisterEventHandler(mEventHandler);
    }

    /**
     * 登录
     *
     * @param account  账号
     * @param password 密码
     */
    private void login(String account, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("humanAccount", account);
        map.put("humanPassword", password);
        map.put("loginStatus","2");
        ObservableHelper.createObservable(RetrofitHelper.createService().loginWithPwd(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        HumanItem item = humanItemBaseItem.getObjValue();
                        HumanCache.saveHumanInfo(mContext, item);
                        finish();
//                        startThenFinish(MainActivity.class);
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在登录");
                    }
                });

    }

    /**
     * 更新用户信息
     *
     * @param account   更新字段
     * @param pwd 更新数据
     */
    private void resetPwd(String account, String pwd) {
        Map<String, String> map = new HashMap<>();
        map.put("humanAccount", account);
        map.put("humanPassword", pwd);
        ObservableHelper.createObservable(RetrofitHelper.createService().updatePwd(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        login(mEtPhone.getText().toString(),mEtPwd.getText().toString());
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showToast("正在重置密码");
                    }
                });
    }
}
